import { defineStore } from 'pinia'
import request from '@/utils/request'
import { topCategory } from '../constants'
import { CateItem, ApiRes, TopCategory, SubCategory } from '@/types/data'
// 导入分类数据 进行遍历得到一个数组包对象的数组
const deafaultCate = topCategory.map((item) => ({ name: item }))
const useCategoryStore = defineStore('categoty', {
  // 共享的数据
  state() {
    return {
      cateList: deafaultCate as CateItem[], // 分类数据
      // 一级商品分类的数据
      topCategory: {} as TopCategory,
      // 二级商品分类的数据
      subCategory: {} as SubCategory,
    }
  },
  actions: {
    // 获取分类列表的数据
    async getCateList() {
      const res = await request.get<ApiRes<CateItem[]>>('/home/category/head')
      // 获取到数据后手动添加show字段
      res.data.result.forEach((item) => (item.show = false))
      this.cateList = res.data.result
    },
    // 改变show值为true
    show(id: string) {
      // console.log(id)
      this.cateList.find((item) => item.id === id)!.show = true
    },
    // 改变show值为false
    hide(id: string) {
      this.cateList.find((item) => item.id === id)!.show = false
    },
    // 获取一级分类的信息方法
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategory>>('/category', {
        params: { id },
      })
      this.topCategory = res.data.result
    },
    // 获取二级分类信息的方法
    async getSubCategory(id: string) {
      const res = await request.get('/category/sub/filter', { params: { id } })
      // const res = await request.get(`/category/sub/filter?id=${id}`)
      this.subCategory = res.data.result
    },
  },

})
export default useCategoryStore
